<?php 

class Yamb {

	private $_data_filename = "yamb.dat";
	public $root = "";
	
	public function __construct() {
		
	}
	
	private function parseTemplate($path) {
		$file_contents = @file_get_contents($path)."";
		if(strlen($file_contents)) {
			$items = preg_split('/(\{\$.*?\})/',$file_contents,-1,PREG_SPLIT_DELIM_CAPTURE);
			$ret = "";
			foreach($items as $line) {
				if(preg_match('/^\{\$/', $line)) {
					$param = preg_replace('/^\{\$|\}$/',"",$line);
					$ret .= @$this->{$param};
				}else{
					$ret .= $line;
				}
			}
			return $ret;
		}
	}
	
	public function index() {
		echo $this->parseTemplate("_index.html");
	}
	
	public function record($result, $mode="read") {
		switch($mode) {
			default:
			case "read":
				$data = $this->_get_data();
				break;
				
			case "write":
				$written = $this->_set_data("record", $result);
				$data = $this->_get_data();
				break;
		}
	}
	
	private function _get_data() {
		if(!file_exists($this->_data_filename)) {
			touch($this->_data_filename);
		}
		$data = array();
		$size = filesize($this->_data_filename);
		if($size>0) {
			$fp = fopen($this->_data_filename, "r");
			if($fp) {
				$source = fread($fp, $size);
				$text = $this->_unpack($source);
				preg_match_all('/(.*?)=([^\r\n]*)[\r\n]*/',$text, $matches);
				if(isset($matches[1])) {
					foreach($matches[1] as $k=>$v) {
						$data[trim($v)] = trim($matches[2][$k]);
					} 
				}
				fclose($fp);
			}
		}
		return $data;
	}
	
	private function _set_data($key, $value) {
		$data = $this->_get_data();
		$data[$key] = $value;
		$fp = fopen($this->_data_filename, "w");
		if(!$fp) {
			return false;
		}
		
		$_data = "";
		foreach ($data as $k=>$v) {
			$_data .= "$k=$v\r\n";
		}
		
		$written = fwrite($fp,$this->_pack($_data));
		fclose($fp);
		return $written;
	}
	
	private function _pack($string) {
		$ret = "";
		for($i=0; $i<strlen($string)-1; $i++) {
			$c = substr($string,$i,1)."yamb";
			$ret .= base64_encode($c);
		}
		return $ret;
	}
	
	private function _unpack($string) {
		$ret = $string;
		$tmp = base64_decode($string);
		echo $tmp."<br />$string";
		return $ret;
	}
}

?>